<template>
  <div class="dashboard-view">
    <h1 class="page-title">
      <Icon icon="lucide:layout-dashboard" width="28" height="28" />
      仪表盘
    </h1>

    <!-- 统计卡片 -->
    <el-row :gutter="24" class="stats-grid">
      <el-col :xs="24" :sm="12" :md="6">
        <div class="stats-card" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
          <Icon icon="lucide:book" width="24" height="24" />
          <div class="stats-value">{{ stats.bookCount || 0 }}</div>
          <div class="stats-label">总书籍数</div>
        </div>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <div class="stats-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
          <Icon icon="lucide:users" width="24" height="24" />
          <div class="stats-value">{{ stats.userCount || 0 }}</div>
          <div class="stats-label">总用户数</div>
        </div>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <div class="stats-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
          <Icon icon="lucide:book-open" width="24" height="24" />
          <div class="stats-value">{{ stats.borrowedCount || 0 }}</div>
          <div class="stats-label">借阅中</div>
        </div>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <div class="stats-card" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
          <Icon icon="lucide:check-circle" width="24" height="24" />
          <div class="stats-value">{{ stats.availableCount || 0 }}</div>
          <div class="stats-label">可借阅</div>
        </div>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="24" class="charts-grid" style="margin-top: 24px;">
      <el-col :xs="24" :lg="12">
        <el-card class="card-container">
          <template #header>
            <div class="card-header">
              <span>借阅趋势（最近7天）</span>
            </div>
          </template>
          <v-chart
            class="chart"
            :option="borrowTrendOption"
            :autoresize="true"
          />
        </el-card>
      </el-col>

      <el-col :xs="24" :lg="12">
        <el-card class="card-container">
          <template #header>
            <div class="card-header">
              <span>热门书籍 TOP 5</span>
            </div>
          </template>
          <v-chart
            class="chart"
            :option="popularBooksOption"
            :autoresize="true"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 分类统计 -->
    <el-row :gutter="24" style="margin-top: 24px;">
      <el-col :span="24">
        <el-card class="card-container">
          <template #header>
            <div class="card-header">
              <span>书籍分类统计</span>
            </div>
          </template>
          <v-chart
            class="chart"
            :option="categoryOption"
            :autoresize="true"
          />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Icon } from '@iconify/vue'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import { TitleComponent, TooltipComponent, LegendComponent, GridComponent } from 'echarts/components'
import { getDashboardData } from '@/api/statistics'

// 注册ECharts组件
use([
  CanvasRenderer,
  BarChart,
  LineChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const stats = ref({})
const borrowTrendOption = ref({})
const popularBooksOption = ref({})
const categoryOption = ref({})

const loadDashboardData = async () => {
  try {
    const response = await getDashboardData()
    if (response.data.code === 200) {
      stats.value = response.data.data

      // 借阅趋势图
      borrowTrendOption.value = {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: response.data.data.borrowTrend.map(item => item.date)
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '借阅量',
            type: 'line',
            smooth: true,
            data: response.data.data.borrowTrend.map(item => item.count),
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0,
                  color: 'rgba(102, 126, 234, 0.5)'
                }, {
                  offset: 1,
                  color: 'rgba(102, 126, 234, 0.1)'
                }]
              }
            },
            itemStyle: {
              color: '#667eea'
            }
          }
        ]
      }

      // 热门书籍图
      popularBooksOption.value = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'value'
        },
        yAxis: {
          type: 'category',
          data: response.data.data.popularBooks.map(item => item.title).reverse()
        },
        series: [
          {
            name: '借阅次数',
            type: 'bar',
            data: response.data.data.popularBooks.map(item => item.borrowCount).reverse(),
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 1,
                y2: 0,
                colorStops: [{
                  offset: 0,
                  color: '#667eea'
                }, {
                  offset: 1,
                  color: '#764ba2'
                }]
              }
            }
          }
        ]
      }

      // 分类统计饼图
      const categoryData = Object.entries(response.data.data.categoryStats).map(([key, value]) => ({
        name: getCategoryName(key),
        value
      }))

      categoryOption.value = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '书籍分类',
            type: 'pie',
            radius: '60%',
            data: categoryData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
    }
  } catch (error) {
    console.error('加载仪表盘数据失败:', error)
  }
}

const getCategoryName = (key) => {
  const map = {
    'LITERATURE': '文学',
    'TECHNOLOGY': '科技',
    'HISTORY': '历史',
    'ART': '艺术',
    'OTHER': '其他'
  }
  return map[key] || key
}

onMounted(() => {
  loadDashboardData()
})
</script>

<style scoped>
.dashboard-view {
  padding: 0;
}

.stats-grid {
  margin-bottom: 24px;
}

.stats-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px;
  padding: 24px;
  transition: transform 0.3s ease;
  height: 100%;
}

.stats-card:hover {
  transform: translateY(-4px);
}

.stats-card .stats-value {
  font-size: 32px;
  font-weight: 700;
  margin: 12px 0 8px;
}

.stats-card .stats-label {
  font-size: 14px;
  opacity: 0.9;
}

.charts-grid .card-container {
  min-height: 400px;
}

.chart {
  height: 350px;
}

.card-header {
  font-weight: 600;
  color: #303133;
}
</style>
